//
//  HMComposeView.swift
//  MicroBlog
//
//  Created by Apple on 16/9/27.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
import pop
class HMComposeView: UIView {
    //读取plist文件
    private lazy var composeMenuArray: [HMComposeMenu] = self.loadComposePlistData()
    //记录6个菜单按钮
    private lazy var buttonArray: [HMComposeButton] = [HMComposeButton]()
    //懒加载控件
    private lazy var sloganImageView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    //记录当前控制器
    var target: UIViewController?
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.size = CGSize(width: ScreenWidth, height: ScreenHeight)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        //获取模糊效果图片
        let image = UIImage.screenShot().applyLightEffect()
        let bgImageView = UIImageView(image: image)
        addSubview(bgImageView)
        addSubview(sloganImageView)
        
        sloganImageView.snp_makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        addChildButton()
    }
    
    //开启弹簧动画效果
    private func startPopAnimation(isUp: Bool) {
        //按钮下移,数组反转遍历
        if isUp == false {
            //数组反转
            buttonArray = buttonArray.reversed()
        }
        //遍历按钮数组
        for (i,button) in buttonArray.enumerated() {
            let popAnimation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            //目的地:需要转成结构体
            if isUp {
                popAnimation?.toValue = NSValue(cgPoint: CGPoint(x: button.centerX, y: button.centerY - 350))
            } else {
                popAnimation?.toValue = NSValue(cgPoint: CGPoint(x: button.centerX, y: button.centerY + 350))
            }
            //动画初始速度
            popAnimation?.springSpeed = 10
            //抖动幅度
            popAnimation?.springBounciness = 10
            //开始动画时间 系统的绝对时间
            popAnimation?.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            //执行动画
            button.pop_add(popAnimation, forKey: nil)
        }
    }
    
    //添加子按钮
    private func addChildButton() {
        //按钮大小
        let buttonWidth:CGFloat = 80
        let buttonHeight:CGFloat = 110
        //按钮间距
        let buttonMargin:CGFloat = (width - 3 * buttonWidth) / 4
        
        for i in 0..<composeMenuArray.count {
            //列
            let col = i % 3
            //行
            let row = i / 3
            //获取模型
            let composeMenu = composeMenuArray[i]
            let button = HMComposeButton()
            //设置tag
            button.tag = i
            button.addTarget(self, action: #selector(buttonAction(btn:)), for: .touchUpInside)
            button.x = CGFloat(col) * buttonWidth + (CGFloat(col) + 1) * buttonMargin
            button.y = CGFloat(row) * buttonWidth + CGFloat(row) * buttonMargin + ScreenHeight
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            button.setImage(UIImage(named: composeMenu.icon!), for: .normal)
            button.setTitle(composeMenu.title!, for: .normal)
            addSubview(button)
            buttonArray.append(button)
        }
    }
    
    //点击事件
    @objc private func buttonAction(btn: UIButton) {
        UIView.animate(withDuration: 0.25, animations: {
            for button in self.buttonArray {
                button.alpha = 0.2
                if button == btn {
                    //点击的按钮,放大
                    button.transform = CGAffineTransform(scaleX: 2, y: 2)
                } else {
                    //其他按钮缩小
                    button.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
                }
            }
        }) { (_) in
            UIView.animate(withDuration: 0.25, animations: {
                for button in self.buttonArray {
                    button.alpha = 1
                    button.transform = CGAffineTransform.identity
                    
                }
                }, completion: { (_) in
                    //跳转控制器
                    //1.自定义的类直接通过类名转成相应的class不行,需要加上命名空间(工程名)
                    //2.转成的class不能直接初始化,需要转换成相应的类型(类名+.type)
                    //3.最后通过class转成响应的对象
                    //获取模型
                    let composeMenu = self.composeMenuArray[btn.tag]
                    //获取按钮对象的类
                    let classType = NSClassFromString(composeMenu.className!)! as! UIViewController.Type
                    //创建对象
                    let vc = classType.init()
                    //放入导航控制器中
                    let nav = HMNaviViewController(rootViewController: vc)
                    self.target?.present(nav, animated: true, completion: {
                        //移除罩层
                        self.removeFromSuperview()
                    })
            })
        }
    }
    
    func show(target: UIViewController){
        self.target = target
        //        //最上层的window
        //        let window = UIApplication.shared.windows.last!
        //        window.addSubview(self)
        //将试图添加到传入的控制器上
        target.view.addSubview(self)
        //添加到目标控制器之后才开启动画
        startPopAnimation(isUp: true)
    }
    
    //读取Plist文件
    private func loadComposePlistData() -> [HMComposeMenu]{
        //获取路径
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)
        //获取数据
        let dicArray = NSArray(contentsOfFile: path!)!
        //字典转模型
        let modelArray = NSArray.yy_modelArray(with: HMComposeMenu.self, json: dicArray)! as! [HMComposeMenu]
        return modelArray
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        startPopAnimation(isUp: false)
        //移除罩层
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
            self.removeFromSuperview()
        }
    }
}
